package com.sinven.daoImpl;

import com.sinven.dao.UserDao;
import com.sinven.entity.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Repository("UserDao")
public class UserDaoImpl implements UserDao{

    @Autowired
    @Qualifier("hibernateTemplate")
    private HibernateTemplate hibernateTemplate;

    @Autowired
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;


    @Override
    public List<User> findUser(String hql) {
        Session currentSession = sessionFactory.getCurrentSession();
        Query query = currentSession.createQuery(hql);
        return query.list();
    }

    @Override
    public List<User> findUserByCode(String username, String password) {
        String hql = "from User where username = :username and password = :password";
        Session currentSession = sessionFactory.getCurrentSession();
        Query query = currentSession.createQuery(hql);
        query.setParameter("username",username);
        query.setParameter("password",password);
        return query.list();
    }




    @Override
    public int RegisteredUser(User user) {
        Session currentSession = sessionFactory.getCurrentSession();
        Serializable result = currentSession.save(user);
        Integer integer = (Integer) result;
        return integer;
    }


    @Override
    public int upLoginTime(Date lastLoginTime,String username) {
        String hql = "update User  set lastLoginTime = :lastLoginTime where username = :username";
        Session currentSession = sessionFactory.getCurrentSession();
        Query query = currentSession.createQuery(hql);
        query.setParameter("lastLoginTime",lastLoginTime);
        query.setParameter("username",username);
        int result = query.executeUpdate();
        return result;
    }
}
